package com.ttc.mBackupK16.BackupSMS;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.ttc.mBackupK16.R;
import com.ttc.mBackupK16.BackupStorage.SDCard;

public class SMSListActivity extends Activity implements OnClickListener{
	
	private SMSQuery smsQuery;
	private SMSClass smsClass;
	private ArrayList<SMSClass> arraySMSClass=new ArrayList<SMSClass>();
	private String m_id;
	private String m_body;
	private String m_address;
	private ArrayList<String> m_ArrayIdSMS;
	private ArrayList<SMSClassCustomViewGroup> arraySMSClassCustomViewGroup;
	SMSListArrayAdapter smsArrayAdapter;
	private ListView lstView;
	private Button btnBackupSMS, btnCancelSMS;
	private CheckBox chbCheckAllSMS;
	private Cursor cursorsmsquery;
	private SDCard sdCard;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		smsQuery=new SMSQuery(getApplicationContext());
		smsClass= new SMSClass();
		
		setContentView(R.layout.sms_list);
		
		btnBackupSMS=(Button)findViewById(R.id.btnBackupSMS);
		btnCancelSMS = (Button)findViewById(R.id.btnCancelSMS);
		chbCheckAllSMS = (CheckBox)findViewById(R.id.chbCheckAllSMS);
		lstView= (ListView) findViewById(R.id.listSMS);
		
		btnBackupSMS.setOnClickListener(this);
		btnCancelSMS.setOnClickListener(this);
		chbCheckAllSMS.setOnClickListener(this);
		
		cursorsmsquery=smsQuery.getAllSMS();
		getSMSForDisplay();	
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btnBackupSMS:
			btnBackup_Click();
			break;
		case R.id.btnCancelSMS:
			this.finish();
			break;
		case R.id.chbCheckAllSMS:
			chbCheckAllSMS_Click();
			break;
		default:
			break;
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater=getMenuInflater();
		inflater.inflate(R.menu.menu_list_sms, menu);
		return true;
	}
	
	/* Function for click menu
	 * (non-Javadoc)
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override 
	public boolean onMenuItemSelected(int featureId,MenuItem item)
	{
		int id=(item.getItemId());
		Log.d("Menu",Integer.toString(item.getItemId()));
		switch (id)
		{
			case R.id.menu_AllSMS:
				Log.d("menu_AllSMS",Integer.toString(item.getItemId()));
				cursorsmsquery=smsQuery.getAllSMS();
				getSMSForDisplay();
				return true;
			case R.id.menu_Inbox:
				Log.d("menu_Inbox",Integer.toString(item.getItemId()));
				cursorsmsquery=smsQuery.getInboxSMS();
				getSMSForDisplay();
				return true;
			case R.id.menu_Sent:
				Log.d("menu_Sent",Integer.toString(item.getItemId()));
				cursorsmsquery=smsQuery.getOutboxSMS();
				getSMSForDisplay();
				return true;
			case R.id.menu_Draft:
				Log.d("menu_Draft",Integer.toString(item.getItemId()));
				getSMSForDisplay();
				return true;
							
		}
		//Log.d("Menu",Integer.toString(item.getItemId()));
		return super.onMenuItemSelected(featureId, item);
	}

	public void btnBackup_Click() {
		try
		{
			if(arraySMSClass.isEmpty()==false)
				arraySMSClass.clear();
			if(lstView.getCount()>0)
			{
				Adapter adapterSMSList=lstView.getAdapter();
				Log.d("LstView", Integer.toString(lstView.getCount()));
				for(int i=0;i<lstView.getCount();i++)
				{
					SMSClassCustomViewGroup objSMSClassCustomViewGroup=(SMSClassCustomViewGroup)adapterSMSList.getItem(i);
					if(chbCheckAllSMS.isChecked())
					{
						smsClass = getSMS(objSMSClassCustomViewGroup.getId().toString());
						arraySMSClass.add(smsClass);
					}
				}
				convertSMSToJSon();
			}
		}
		catch(Exception ex)
		{
			throw new RuntimeException(ex);
		}
		/*Log.i("ArrayAdapter", Integer.toString(smsArrayAdapter.getCount()));
		

		if (smsArrayAdapter.arrayIdSMS != null) {
			if (smsArrayAdapter.arrayIdSMS.isEmpty()) {
				Log.i("tag", "m_ArrayIdSMSEmpty");
			} else {
				Log.i("idsms", smsArrayAdapter.arrayIdSMS.get(0).toString());
				arraySMSClass = new ArrayList<SMSClass>(
						smsArrayAdapter.arrayIdSMS.size());
				try {
					for (int i = 0; i < smsArrayAdapter.arrayIdSMS.size(); i++) {
						smsClass = getSMS(smsArrayAdapter.arrayIdSMS.get(i)
								.toString());
						arraySMSClass.add(smsClass);
					}
					convertSMSToJSon();
				} catch (Exception ex) {
					throw new RuntimeException(ex);
				}
				Log.i("tag", Integer.toString(arraySMSClass.size()));
			}
		}
		*/
	}
	public void chbCheckAllSMS_Click()
	{
		try
		{
			//declare the list SMSClassCustomViewGroup to contain each item in list View
			ArrayList<SMSClassCustomViewGroup> lstSMSClassCustomViewGroup= new ArrayList<SMSClassCustomViewGroup>();
			//get all item in list view current 
			Adapter adapterSMSList=lstView.getAdapter();
			Log.d("LstView", Integer.toString(lstView.getCount()));
			for(int i=0;i<lstView.getCount();i++)
			{
				SMSClassCustomViewGroup objSMSClassCustomViewGroup=(SMSClassCustomViewGroup)adapterSMSList.getItem(i);
				if(chbCheckAllSMS.isChecked())
					objSMSClassCustomViewGroup.setChecked(true);
				else
					objSMSClassCustomViewGroup.setChecked(false);
				
				lstSMSClassCustomViewGroup.add(objSMSClassCustomViewGroup);
			}
			smsArrayAdapter= new SMSListArrayAdapter(this, R.layout.sms_list, arraySMSClassCustomViewGroup);
			if(lstView.getCount()>0)
				lstView.removeAllViewsInLayout();
			lstView.setAdapter(smsArrayAdapter);
		
		}
		catch(Exception ex)
		{
			throw new RuntimeException(ex);
		}
		
	}
	public SMSClass getSMS(String IdSMS) {
		return smsQuery.getSMSById(IdSMS);
	}

	public void convertSMSToJSon()
	{
		
		StringBuilder buiderJSon= new StringBuilder();
		GsonBuilder gSonBuider= new GsonBuilder();
		Gson gSon=gSonBuider.create();
		
		try
		{
			for(int i=0;i< arraySMSClass.size();i++)
			{
				//Log.i("json",s);
				buiderJSon.append(gSon.toJson(arraySMSClass.get(i)));
				Log.i("json",buiderJSon.toString());
	
			}
		}
		catch(JsonParseException ex)
		{
			Toast.makeText(this, "Have Error to parse to Json", Toast.LENGTH_LONG);
		}
		
		writeFileSDCard(buiderJSon);
	}
	public Boolean writeFileSDCard(StringBuilder strBuilder)
	{
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd", Locale.US);
		String filename = "SMS" + sdf.format(new Date())+".txt";
		
		try {
			String root = Environment.getExternalStorageDirectory().toString();
			String backupFile = root;
			File dir;
			/*for(int i = 1; i< item.length - 1; i++){
				backupFile += "/" + item[i];
				dir = new File(backupFile);
				if (!dir.exists())
					dir.mkdirs();
			}*/
			
			//backupFile += "/" + item[item.length - 1];
			File f = new File(backupFile+"/"+filename);
			FileWriter fw;
			try {
				fw = new FileWriter(f);

				fw.write(strBuilder.toString());
				fw.flush();
				fw.close();
				Log.i("contact", "Saved file " + backupFile + " to sd card");
				return true;
			} catch (IOException e1) {
				Log.i("contact", "Error: " + e1.getMessage());
				e1.printStackTrace();
				return false;
			}
		} catch (Exception e) {
			Log.e("contact", e.getMessage());
			return false;
		}
	}
	
	/*
	 *	Name 	: Get SMS from SQL
	 *	Input Value: 
	 *	Output Value
	 *	Description: Get SMS from SQL,Draft,Inbox,Sent or all SMS
	 */
	public void getSMSForDisplay()
	{
		arraySMSClassCustomViewGroup= new ArrayList<SMSClassCustomViewGroup>();
		cursorsmsquery.moveToFirst();
		do
		{
			 m_id= cursorsmsquery.getString(cursorsmsquery.getColumnIndex("_id"));
			 m_body=cursorsmsquery.getString(cursorsmsquery.getColumnIndex("body"));
			 m_address=cursorsmsquery.getString(cursorsmsquery.getColumnIndex("address"));
			 SMSClassCustomViewGroup smsClassCustomViewGroup= new SMSClassCustomViewGroup(m_body, m_address, m_id, false);
			 arraySMSClassCustomViewGroup.add(0,smsClassCustomViewGroup);
			 
			 cursorsmsquery.moveToNext();
		}while(!cursorsmsquery.isLast());
		smsArrayAdapter= new SMSListArrayAdapter(this, R.layout.sms_list, arraySMSClassCustomViewGroup);
		
		
		if(lstView.getCount()>0)
			lstView.removeAllViewsInLayout();
		lstView.setAdapter(smsArrayAdapter);
		
	}
}
